<?php
declare(strict_types=1);

namespace app\api\service;
use app\api\model\UploadFile;
use app\common\library\helper;
use app\common\model\lottery\LotteryParticipant;
use app\common\model\lottery\Manage;
use app\common\service\BaseService;
use think\facade\Cache;
use think\facade\Db;
use app\common\model\Seckill as SeckillModel;

/**
 * 活动
 */
class Activity extends BaseService
{
    //首页
    public function getIndex($access_token):array
    {
        return  [
            'lottery' => $this->getLotteryList($access_token),
            'seckill' => $this->getSecKillList(),
        ];
    }


    //获取抽选列表
    public function getLotteryList($access_token): array
    {
        return Manage::with(['cover'])
            ->where('status',1)
            ->where('is_del',0)
            ->field('id,name,cover_id,start_time,end_time,sort,open_status')
            ->order(['sort' => 'ASC','id' => 'DESC'])
            ->select()
            ->each(function (&$item) use($access_token){
                $item['cover_url'] = $item['cover']['preview_url'] ?? '';
                $item['current_time'] = time();
                unset($item['cover']);
                $item['is_participant'] = self::getHasParticipant($item['id'],$access_token);
            })
            ->toArray();
    }


    //获取秒杀（非售空 已结束）
    public function getSecKillList(): array
    {
        $map1 = [
            ['start_time', '=', null],
            ['end_time', '=', null],
            ['status', '=', 1],
            ['is_del','=',0],
            ['store_id','=',$this->storeId]
        ];

        $map2 = [
            ['start_time','<',date('Y-m-d H:i:s')],
            ['end_time','>',date('Y-m-d H:i:s')],
            ['status', '=', 1],
            ['is_del','=',0],
            ['store_id','=',$this->storeId],
        ];

        $list =  Db::name('seckill_activity')->whereOr([$map1,$map2])
            ->field('id,name,start_time,end_time,image_id,price,origin_price,sale,
            hot_words,quantity,sort')
            ->order(['sort' => 'ASC','id' => 'DESC'])
            ->where('(quantity - sale)>0')
            ->select()
            ->toArray();
        if(!empty($list)){
            foreach ($list as &$item){
                $image_ids = helper::jsonDecode($item['image_id']);
                $image_urls = [];
                foreach ($image_ids as $image_id){
                    $image_info = UploadFile::detail($image_id);
                    $image_urls[] = $image_info->preview_url;
                }
                $item['img_url'] = $image_urls;
                $item['hot_words'] = helper::jsonDecode($item['hot_words']);
                unset($item['image_id']);
            }
        }
        return $list;
    }

    //获取当前用户是否参与抽选活动状态
    public static function getHasParticipant($lottery_id,$access_token): int
    {
        $is_participant = 0;
        if($access_token){
            $userId = Cache::get($access_token)['user']['user_id'] ?? 0;
            if($userId){
                $lott = LotteryParticipant::where('lottery_id',$lottery_id)->where('user_id',$userId)->find();
                if($lott){
                    $is_participant = 1;
                }
            }
        }
        return $is_participant;


    }

}